//
//  NLWebViewController.swift
//  sinaWeibo7110
//
//  Created by 安静清晨 on 2017/1/7.
//  Copyright © 2017年 walk-in-minds. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class NLOAuthViewController: UIViewController {
    
    let webView = UIWebView()
    
    //直接设置webview为VC的根视图
    override func loadView(){
        
        view = webView
        webView.delegate = self
        
    }
    
    

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        
        //左上方关闭按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", imageName: "", target: self, action: #selector(closeIt))
        //走后门按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: " 走后门", imageName: "", target: self, action: #selector(addUserIdAndPwd))
        
        
        
        loadOAuthPage()
        
    }

    @objc private func addUserIdAndPwd(){
        
        let jsString = "document.getElementById('userId').value = '2455115436@qq.com',document.getElementById('passwd').value = 'mingfan11'"
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    
    
    @objc private func closeIt(){
        
       dismiss(animated: true, completion: nil)
        
    }
    
    
    // 请求新浪登录页面
    private func loadOAuthPage(){
        //code=e27b5b1110afae509a405b9ccaa8bff3
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=2407537838&redirect_uri=https://www.douban.com/"
        let url = URL(string: urlString)
        let req = URLRequest(url: url!)
        webView.loadRequest(req)
        
    }
    
    
    //1. 获取code
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.url?.absoluteString ?? ""
        
        //print("=====urlString", urlString)
        
        let flag = "code="
        
        if urlString .contains(flag) {
            
            //query获得url的参数部分
            let query = request.url?.query ?? ""
            let code = (query as NSString).substring(from: flag.characters.count)
            //print("========code",code)
            //2.通过code获取令牌
            //通过ViewModel的单例对象来获取令牌
            NLUserAccountViewModel.shared.loadAccessToken(code: code, finished: { (success) in
                
                if !success{
                    
                    SVProgressHUD.showError(withStatus: "网络有问题")
                    return
                }
                    
                    print("用户登录成功了")
//                  //MARK:problem
                    //需要在从未登录到登录以后 让单例中的account有值->问题在于 在哪里赋值
                    //跳到欢迎控制器-----把欢迎控制器设为根控制器
                
                //MARK:不跳
                    UIApplication.shared.keyWindow?.rootViewController = NLWelcomeViewController()
                    
                    
                
                    
                
                
            })
//            loadAccessToken(code: code)
            return false
            
        }
        return true
    }
    
//    //2.通过code获取令牌 access_token
//    private func loadAccessToken(code:String){
//        
//        //https://api.weibo.com/oauth2/access_token, POST请求
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//        
//        //参数-字典
//        let dict = ["client_id":client_id,
//                    "client_secret":client_secret,
//                    "grant_type":grant_type,
//                    "code":code,
//                    "redirect_uri":redirect_uri]
//        
//        HMNetworkTools.shared.request(method: .POST, urlString: urlString, parameters: dict, finished: {(resp, error)->() in
//            
//            if error != nil{
//                
//                //提示错误
//                SVProgressHUD.showError(withStatus: "我的娘诶你咋没网了")
//                return
//                
//            }else{
//                
//                print(resp!)
//                //3.通过令牌请求用户信息
//                self.loadUserInfo(dict:resp as! [String : Any])
//            }
//            
//        })
//        
//    }
//    
//    private func loadUserInfo(dict:[String:Any]){
//        
//        
//        //参数: access_token  uid
//        let access_token = dict["access_token"]!
//        let uid = dict["uid"]!//MARK:有可能会有问题, 有问题的时候这里加!
//        let parameters = ["access_token" : access_token,
//                          "uid" : uid]
//        print(parameters)
//        let urlString = "https://api.weibo.com/2/users/show.json"
//        HMNetworkTools.shared.request(method: .GET, urlString: urlString, parameters: parameters) { (resp, error) in
//            if error != nil {
//                //错误提示
//                SVProgressHUD.showError(withStatus: "世界上最遥远的举例就是没有网络")
//                return
//            }
//            
//            print(resp!)
//            var userInfoDict = resp as! [String:Any]
//            //3.1将令牌字典合并到用户信息字典
//            for (key,value) in dict{
//                
//                userInfoDict[key] = value
//                
//            }
//            //3.2字典转模型
//            let userAccount = NLUserAccount(dict:userInfoDict)
//            
//            //4. 将模型数组 归档
//            self.saverUserAccount(account: userAccount)
//        }
//    }
//    
//    
//    //4. 将用户信息归档
//    private func saverUserAccount(account:NLUserAccount){
//        // 在String中没有拼接文件路径的方法 需要转换为NSString
//        let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("account.plist")
//        NSKeyedArchiver.archiveRootObject(account, toFile: path)
//        print(path)
//    }
//    
    override func viewWillDisappear(_ animated: Bool) {
        
        SVProgressHUD.dismiss()
    }
    
}
    
    
    //在分类中实现协议方法
    extension NLOAuthViewController:UIWebViewDelegate {
        
        
        func webViewDidStartLoad(_ webView: UIWebView){
            
            SVProgressHUD.show()
            
        }
        
        
        func webViewDidFinishLoad(_ webView: UIWebView){
            
            SVProgressHUD.dismiss()
        }
    }
    
    


